package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.CurrentUser;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.customer.mapper.AgencyCertificationAuditMapper;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.domain.AgencyCertificationAudit;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.AgencyCertificationAuditResDTO;
import com.jzo2o.customer.model.dto.response.CertificationStatusDTO;
import com.jzo2o.customer.service.IAgencyCertificationAuditService;
import com.jzo2o.customer.service.IAgencyCertificationService;
import com.jzo2o.customer.service.IServeProviderService;
import com.jzo2o.mvc.handler.UserInfoHandlerImpl;
import com.jzo2o.mysql.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author: LiuLi
 * @Date: 2025/09/18 上午11:39
 * @Description: 机构认证审核服务实现类
 */
@Service
@Slf4j
public class AgencyCertificationAuditServiceImpl extends ServiceImpl<AgencyCertificationAuditMapper, AgencyCertificationAudit> implements IAgencyCertificationAuditService {

    @Resource
    private IAgencyCertificationService agencyCertificationService;
    @Resource
    private IAgencyCertificationAuditService agencyCertificationAuditService;
    @Resource
    private UserInfoHandlerImpl userInfoHandlerImpl;
    @Resource
    private IServeProviderService serveProviderService;

    /**
     * 添加机构认证信息
     *
     * @param agencyCertificationAuditAddReqDTO 机构认证信息
     */
    @Override
    public void add(AgencyCertificationAuditAddReqDTO agencyCertificationAuditAddReqDTO) {
        // 将请求DTO转换为实体类
        AgencyCertificationAudit agencyCertificationAudit = BeanUtil.toBean(agencyCertificationAuditAddReqDTO, AgencyCertificationAudit.class);

        // 设置默认值
        agencyCertificationAudit.setAuditStatus(0); // 0：未审核
        agencyCertificationAudit.setCertificationStatus(1); // 1：认证中
        agencyCertificationAudit.setCreateTime(LocalDateTime.now());
        agencyCertificationAudit.setUpdateTime(LocalDateTime.now());

        // 保存到agency_certification_audit表
        this.save(agencyCertificationAudit);

        log.info("机构认证申请保存成功，机构ID：{}", agencyCertificationAudit.getServeProviderId());
    }

    /**
     * 分页查询认证申请信息
     *
     * @param queryDTO 查询参数
     * @return 分页结果
     */
    @Override
    public PageResult<AgencyCertificationAuditResDTO> pageQuery(AgencyCertificationAuditPageQueryReqDTO queryDTO) {
        // 解析分页参数
        Page<AgencyCertificationAudit> page = PageUtils.parsePageQuery(queryDTO, AgencyCertificationAudit.class);

        // 构建查询条件
        LambdaQueryWrapper<AgencyCertificationAudit> queryWrapper = new LambdaQueryWrapper<>();

        // 按企业名称模糊查询
        if (queryDTO.getName() != null) {
            queryWrapper.like(AgencyCertificationAudit::getName, queryDTO.getName());
        }

        // 按法人姓名模糊查询
        if (queryDTO.getLegalPersonName() != null) {
            queryWrapper.like(AgencyCertificationAudit::getLegalPersonName, queryDTO.getLegalPersonName());
        }

        // 按审核状态查询
        if (queryDTO.getAuditStatus() != null) {
            queryWrapper.eq(AgencyCertificationAudit::getAuditStatus, queryDTO.getAuditStatus());
        }

        // 按认证状态查询
        if (queryDTO.getCertificationStatus() != null) {
            queryWrapper.eq(AgencyCertificationAudit::getCertificationStatus, queryDTO.getCertificationStatus());
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc(AgencyCertificationAudit::getCreateTime);

        // 执行分页查询
        Page<AgencyCertificationAudit> agencyCertificationAuditPage = baseMapper.selectPage(page, queryWrapper);

        // 转换为响应DTO并返回
        return PageUtils.toPage(agencyCertificationAuditPage, AgencyCertificationAuditResDTO.class);
    }

    /**
     * 查询机构认证申请失败原因
     *
     * @param serveProviderId 机构id
     * @return 失败原因
     */
    @Override
    public String getRejectReason(Long serveProviderId) {
        // 查询最新的认证申请
        AgencyCertificationAudit latestAudit = baseMapper.getLatestByServeProviderId(serveProviderId);
        if (latestAudit != null && latestAudit.getCertificationStatus() == 3) { // 3：认证失败
            return latestAudit.getRejectReason();
        }
        return null;
    }

    /**
     * 审核机构认证信息
     *
     * @param id                认证审核id
     * @param certificationStatus 认证状态
     * @param rejectReason      驳回原因
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(Long id, Integer certificationStatus, String rejectReason) {
        // 1.校验认证审核是否存在
        AgencyCertificationAudit agencyCertificationAudit = agencyCertificationAuditService.getById(id);
        if (agencyCertificationAudit == null) {
            throw new IllegalArgumentException("认证审核不存在");
        }

        // 2.校验认证审核状态
        if (!agencyCertificationAudit.getAuditStatus().equals(0)) { // 0：未审核
            log.info("认证审核状态异常，当前状态：{}", agencyCertificationAudit.getAuditStatus());
            throw new IllegalArgumentException("认证审核状态异常");
        }

        // 如果认证状态为通过 (2: 认证成功)
        if (Integer.valueOf(2).equals(certificationStatus)) {
            // 3.更新agency_certification_audit里面的认证状态
            AgencyCertificationAudit updateAudit = new AgencyCertificationAudit();
            updateAudit.setAuditStatus(1); // 1: 已审核
            updateAudit.setAuditorId(userInfoHandlerImpl.currentUserInfo().getId());
            updateAudit.setAuditorName(userInfoHandlerImpl.currentUserInfo().getName());
            updateAudit.setAuditTime(LocalDateTime.now());
            updateAudit.setUpdateTime(LocalDateTime.now());
            updateAudit.setCertificationStatus(certificationStatus);
            updateAudit.setRejectReason(rejectReason);
            agencyCertificationAuditService.updateById(updateAudit);

            // 4.更新agency_certification里面的认证状态
            AgencyCertification agencyCertification = new AgencyCertification();
            agencyCertification.setCertificationStatus(2); // 认证成功
            agencyCertification.setUpdateTime(LocalDateTime.now());
            agencyCertification.setCertificationTime(LocalDateTime.now());

            // 使用update wrapper更新认证信息
            com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<AgencyCertification> updateWrapper =
                    com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaUpdate(AgencyCertification.class)
                            .set(AgencyCertification::getCertificationStatus, 2)
                            .set(AgencyCertification::getUpdateTime, LocalDateTime.now())
                            .set(AgencyCertification::getCertificationTime, LocalDateTime.now())
                            .eq(AgencyCertification::getId, agencyCertificationAudit.getServeProviderId());
            agencyCertificationService.update(updateWrapper);

            // 5.更新服务人员表里面的认证状态和设置状态
            com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<ServeProvider> serveProviderUpdateWrapper =
                    com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaUpdate(ServeProvider.class)
                            .set(ServeProvider::getName, agencyCertificationAudit.getName())
                            .set(ServeProvider::getSettingsStatus, 1) // 认证通过后设置状态为1
                            .set(ServeProvider::getUpdateTime, LocalDateTime.now())
                            .eq(ServeProvider::getId, agencyCertificationAudit.getServeProviderId());
            serveProviderService.update(serveProviderUpdateWrapper);

        } else if (Integer.valueOf(3).equals(certificationStatus)) { // 3: 认证失败
            // 3.更新agency_certification_audit里面的认证状态
            AgencyCertificationAudit updateAudit = new AgencyCertificationAudit();
            updateAudit.setAuditStatus(1); // 1: 已审核
            updateAudit.setAuditorId(userInfoHandlerImpl.currentUserInfo().getId());
            updateAudit.setAuditorName(userInfoHandlerImpl.currentUserInfo().getName());
            updateAudit.setAuditTime(LocalDateTime.now());
            updateAudit.setUpdateTime(LocalDateTime.now());
            updateAudit.setCertificationStatus(3); // 认证失败
            updateAudit.setRejectReason(rejectReason);
            agencyCertificationAuditService.updateById(updateAudit);

            // 4.更新agency_certification里面的认证状态
            com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<AgencyCertification> updateWrapper =
                    com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaUpdate(AgencyCertification.class)
                            .set(AgencyCertification::getCertificationStatus, 3) // 认证失败
                            .set(AgencyCertification::getUpdateTime, LocalDateTime.now())
                            .eq(AgencyCertification::getId, agencyCertificationAudit.getServeProviderId());
            agencyCertificationService.update(updateWrapper);

            // 5.更新服务人员表里面的认证状态和设置状态
            com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<ServeProvider> serveProviderUpdateWrapper =
                    com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaUpdate(ServeProvider.class)
                            .set(ServeProvider::getName, agencyCertificationAudit.getName())
                            .set(ServeProvider::getSettingsStatus, 0) // 认证失败后设置状态为0
                            .set(ServeProvider::getUpdateTime, LocalDateTime.now())
                            .eq(ServeProvider::getId, agencyCertificationAudit.getServeProviderId());
            serveProviderService.update(serveProviderUpdateWrapper);
        }

        log.info("机构认证审核完成，认证审核ID：{}，审核结果：{}", id, certificationStatus);
    }

}